package com.cm.figure.controller.imagesController;

import com.cm.figure.model.User;
import com.cm.figure.service.userService.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.OutputStream;

/**
 * ClassName:PictureController
 * Package:com.cm.figure.controller.imagesController
 * Description:
 *
 * @Date:2021/8/15 21:49
 * @com.chuangmei
 */
@Controller
public class ImagesController {

    @Autowired
    private UserService userService;


    @RequestMapping("/test")
    @ResponseBody
    public String test() {
        return "服务器返回数据";
    }

    @RequestMapping("/image/{filename}")
    @ResponseBody
    public void getImagesId(@PathVariable String filename, HttpServletResponse rp) {
        //获取用户id
        String[] value = filename.split("\\.");
        int userid = Integer.parseInt(value[0]);
        // 通过id查询User
        User user = userService.queryUserByUserId(userid);
        //图片在服务器存储位置
        String filePath = user.getFilepath() + "/" + filename;

        File imageFile = new File(filePath);
        if (imageFile.exists()) {
            FileInputStream fis = null;
            OutputStream os = null;
            try {
                fis = new FileInputStream(imageFile);
                os = rp.getOutputStream();
                int count = 0;
                byte[] buffer = new byte[1024 * 8];
                while ((count = fis.read(buffer)) != -1) {
                    os.write(buffer, 0, count);
                    os.flush();
                }
            } catch (Exception e) {
                e.printStackTrace();
            } finally {
                try {
                    fis.close();
                    os.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }



}
